#include <iostream>
#include <vector>
#include <stack>
using namespace std;

class Solution {
	stack<int> tps;
	void dfs(vector<vector<int>> &gh, vector<int> &vis, int u)
	{
		vis[u] = 1;
		for (auto v : gh[u]) {
			if (!vis[v]) {
				dfs(gh, vis, v);
			}
		}
		tps.push(u);
	}

	void top_order(vector<vector<int>> &gh, vector<int> &vis)
	{
		int n = vis.size();
		for (int i = 0; i < n; i++) {
			if (!vis[i]) {
				dfs(gh, vis, i);
			}
		}
	}

    public:
	vector<int> loudAndRich(vector<vector<int>> &richer, vector<int> &quiet)
	{
		int n = quiet.size();
		vector<vector<int>> gh(n);
		vector<int> vis(n, 0), ans(n, 0);

		for (int i = 0; i < n; i++) {
			ans[i] = i;
		}

		for (auto e : richer) {
			gh[e[0]].push_back(e[1]);
		}
		top_order(gh, vis);

		while (!tps.empty()) {
			int u = tps.top();
			tps.pop();

			for (auto v : gh[u]) {
				ans[v] = quiet[ans[u]] < quiet[ans[v]] ? ans[u] : ans[v];
			}
		}
		return ans;
	}
};

int main()
{
	vector<vector<int>> richer = { { 1, 0 }, { 2, 1 }, { 3, 1 }, { 3, 7 }, { 4, 3 }, { 5, 3 }, { 6, 3 } };
	vector<int> quiet = { 3, 2, 5, 4, 6, 1, 7, 0 };
	vector<int> ans = Solution().loudAndRich(richer, quiet);
	for (auto v : ans) {
		cout << v << ' ';
	}
	cout << endl;
	return 0;
}